﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Felbot.Interface.Conversations;
using Felbot.Properties;

namespace Felbot {
    /// <summary>A little form that allows the user to store and use a list of CD-keys.</summary>
    public partial class frmLogViewer : Form {
        /// <summary>Creates a new log viewer form.</summary>
        public frmLogViewer() {
            InitializeComponent();
            LoadLogsTree();
        }

        private void LoadLogsTree() {
            if (!Directory.Exists(Program.ApplicationFolder + "\\Logs"))
                return;
            string[] dirs = Directory.GetDirectories(Program.ApplicationFolder + "\\Logs");
            TreeNode rootNode = new TreeNode("Logs");
            foreach (string dir in dirs) {
                string[] files = Directory.GetFiles(dir);
                if (files.Length > 0) {
                    TreeNode dirNode = new TreeNode(new DirectoryInfo(dir).Name);
                    dirNode.Tag = dir;
                    foreach (string file in files) {
                        FileInfo info = new FileInfo(file);
                        if (info.Extension == ".fbx" || info.Extension == ".fbf") {
                            string stamp = info.Name.Substring(0, info.Name.Length - 4);
                            DateTime logDate;
                            if (DateTime.TryParseExact(stamp, "yyyy-MM-dd", DateTimeFormatInfo.CurrentInfo, DateTimeStyles.AllowWhiteSpaces, out logDate)) {
                                TreeNode logNode = new TreeNode(logDate.ToShortDateString());
                                logNode.Tag = file;
                                StringBuilder tip = new StringBuilder();
                                tip.Append("Log Date: ").AppendLine(logDate.ToLongDateString());
                                tip.Append("Type: ");
                             // if (info.Extension == ".fbx")
                                tip.AppendLine("Rich Text");
                             // else
                             //     tip.AppendLine("Plain Text");
                                tip.Append("Size: ").Append(info.Length).AppendLine(" bytes");
                                tip.Append("Profile: ").Append(new DirectoryInfo(dir).Name);
                                logNode.ToolTipText = tip.ToString();
                                dirNode.Nodes.Add(logNode);
                            }
                        }
                    }
                    rootNode.Nodes.Add(dirNode);
                }
            }
            rootNode.Expand();
            tvLogs.Nodes.Add(rootNode);
        }

        private void tvLogs_AfterSelect(object sender, TreeViewEventArgs e) {
            if (e.Node == null) {
                btnView.Enabled = false;
                btnDelete.Enabled = false;
                return;
            }
            switch (e.Node.Level) {
                case 0: //logs root node
                    btnView.Enabled = false;
                    btnDelete.Enabled = true;
                    break;
                case 1: //logs profile node
                    btnView.Enabled = false;
                    btnDelete.Enabled = true;
                    break;
                case 2: //logs log file node
                    btnView.Enabled = true;
                    btnDelete.Enabled = true;
                    break;
            }
        }

        private void tvLogs_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) {
            if (e.Node == null)
                return;
            if (e.Node.Level == 2)
                ViewLog(e.Node.Tag.ToString());
        }

        private void btnView_Click(object sender, EventArgs e) {
            TreeNode node = tvLogs.SelectedNode;
            if (node == null)
                return;
            if (node.Level == 2)
                ViewLog(node.Tag.ToString());
        }

        private void btnDelete_Click(object sender, EventArgs e) {
            TreeNode node = tvLogs.SelectedNode;
            if (node == null)
                return;
            switch (node.Level) {
                case 0: //logs root node
                    if (MessageBox.Show("Are you sure you want to delete all stored logs?\r\n" +
                                        "They will be deleted forever.",
                                        "Felbot",
                                        MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Warning,
                                        MessageBoxDefaultButton.Button2) == DialogResult.Yes) {
                        Directory.Delete(Program.ApplicationFolder + "\\Logs", true);
                        Directory.CreateDirectory(Program.ApplicationFolder + "\\Logs");
                    }
                    break;
                case 1: //logs profile node
                    Directory.Delete(node.Tag.ToString());
                    node.Remove();
                    break;
                case 2: //logs log file node
                    File.Delete(node.Tag.ToString());
                    node.Remove();
                    break;
            }
        }

        private void btnDone_Click(object sender, EventArgs e) {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void ViewLog(string filePath) {
            new frmLogFileViewer(filePath).ShowDialog();
        }

        private class frmLogFileViewer : Form {
            string m_FilePath;

            public frmLogFileViewer(string filePath) {
                InitializeComponent();
                m_FilePath = filePath;
            }

            private void frmLogFileViewer_Shown(object sender, EventArgs e) {
                rtbLog.SetConversation(ConversationControl.GetConversation(m_FilePath));
                rtbLog.SelectionStart = 0;
                rtbLog.SelectionLength = 0;
                rtbLog.ScrollToCaret();
            }

            private void mnuText_Opening(object sender, CancelEventArgs e) {
                mnuTextCopy.Enabled = (rtbLog.SelectionLength > 0);
            }

            private void mnuTextCopy_Click(object sender, EventArgs e) {
                rtbLog.Copy();
            }

            private void mnuTextSelectAll_Click(object sender, EventArgs e) {
                rtbLog.SelectAll();
            }

            /// <summary>
            /// Required designer variable.
            /// </summary>
            private IContainer components = null;

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
            protected override void Dispose(bool disposing) {
                if (disposing && (components != null)) {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }

            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent() {
                this.components = new Container();
                this.rtbLog = new RichTextBoxEx();
                this.mnuText = new ContextMenuStrip(this.components);
                this.mnuTextCut = new ToolStripMenuItem();
                this.mnuTextCopy = new ToolStripMenuItem();
                this.mnuTextPaste = new ToolStripMenuItem();
                this.mnuTextDelete = new ToolStripMenuItem();
                this.mnuTextSeparator1 = new ToolStripSeparator();
                this.mnuTextSelectAll = new ToolStripMenuItem();
                this.mnuText.SuspendLayout();
                this.SuspendLayout();
                // 
                // rtbOutput
                // 
                this.rtbLog.BackColor = Color.Black;
                this.rtbLog.BorderStyle = BorderStyle.None;
                this.rtbLog.ContextMenuStrip = mnuText;
                this.rtbLog.Dock = DockStyle.Fill;
                this.rtbLog.Location = new Point(0, 0);
                this.rtbLog.Margin = new Padding(4, 4, 4, 4);
                this.rtbLog.Name = "rtbLog";
                this.rtbLog.ReadOnly = true;
                this.rtbLog.Size = new Size(465, 347);
                this.rtbLog.TabIndex = 1;
                this.rtbLog.TabStop = false;
                this.rtbLog.Text = "";
                // 
                // mnuText
                // 
                this.mnuText.Items.AddRange(new ToolStripItem[] {
                    this.mnuTextCut,
                    this.mnuTextCopy,
                    this.mnuTextPaste,
                    this.mnuTextDelete,
                    this.mnuTextSeparator1,
                    this.mnuTextSelectAll});
                this.mnuText.Name = "mnuText";
                this.mnuText.Size = new Size(197, 142);
                this.mnuText.Opening += new CancelEventHandler(mnuText_Opening);
                // 
                // mnuTextCut
                // 
                this.mnuTextCut.Enabled = false;
                this.mnuTextCut.Image = Resources.cut;
                this.mnuTextCut.Name = "mnuTextCut";
                this.mnuTextCut.ShortcutKeys = ((Keys) ((Keys.Control | Keys.X)));
                this.mnuTextCut.Size = new Size(196, 22);
                this.mnuTextCut.Text = "Cut";
                // 
                // mnuTextCopy
                // 
                this.mnuTextCopy.Image = Resources.copy;
                this.mnuTextCopy.Name = "mnuTextCopy";
                this.mnuTextCopy.ShortcutKeys = ((Keys) ((Keys.Control | Keys.C)));
                this.mnuTextCopy.Size = new Size(196, 22);
                this.mnuTextCopy.Text = "Copy";
                this.mnuTextCopy.Click += new EventHandler(mnuTextCopy_Click);
                // 
                // mnuTextPaste
                // 
                this.mnuTextPaste.Enabled = false;
                this.mnuTextPaste.Image = Resources.paste;
                this.mnuTextPaste.Name = "mnuTextPaste";
                this.mnuTextPaste.ShortcutKeys = ((Keys) ((Keys.Control | Keys.V)));
                this.mnuTextPaste.Size = new Size(196, 22);
                this.mnuTextPaste.Text = "Paste";
                // 
                // mnuTextDelete
                // 
                this.mnuTextDelete.Enabled = false;
                this.mnuTextDelete.Name = "mnuTextDelete";
                this.mnuTextDelete.ShortcutKeys = Keys.Delete;
                this.mnuTextDelete.Size = new Size(196, 22);
                this.mnuTextDelete.Text = "Delete";
                // 
                // mnuTextSeparator1
                // 
                this.mnuTextSeparator1.Name = "mnuTextSeparator1";
                this.mnuTextSeparator1.Size = new Size(193, 6);
                // 
                // mnuTextSelectAll
                // 
                this.mnuTextSelectAll.Name = "mnuTextSelectAll";
                this.mnuTextSelectAll.ShortcutKeys = ((Keys) ((Keys.Control | Keys.A)));
                this.mnuTextSelectAll.Size = new Size(196, 22);
                this.mnuTextSelectAll.Text = "Select All";
                this.mnuTextSelectAll.Click += new EventHandler(mnuTextSelectAll_Click);
                // 
                // frmScriptOutput
                // 
                this.AutoScaleDimensions = new SizeF(8F, 16F);
                this.AutoScaleMode = AutoScaleMode.Font;
                this.ClientSize = new Size(640, 480);
                this.Controls.Add(this.rtbLog);
                this.FormBorderStyle = FormBorderStyle.SizableToolWindow;
                this.Margin = new Padding(4, 4, 4, 4);
                this.MaximizeBox = false;
                this.MinimizeBox = false;
                this.Name = "frmScriptOutput";
                this.ShowInTaskbar = false;
                this.Text = "Log File Viewer";
                this.TopMost = true;
                this.mnuText.ResumeLayout(false);
                this.Shown += new EventHandler(frmLogFileViewer_Shown);
                this.ResumeLayout(false);
            }
            #endregion

            private RichTextBoxEx rtbLog;
            private ContextMenuStrip mnuText;
            private ToolStripMenuItem mnuTextCut;
            private ToolStripMenuItem mnuTextCopy;
            private ToolStripMenuItem mnuTextPaste;
            private ToolStripMenuItem mnuTextDelete;
            private ToolStripSeparator mnuTextSeparator1;
            private ToolStripMenuItem mnuTextSelectAll;
        }
    }
}
